from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler
from .serializers import *
from .models import *
from django.core.paginator import Paginator
from django.db.models import Q,F
from datetime import datetime
import os
from meiduo_admin import settings

class CartView(APIView):
    def post(self,request):
        goods_id = request.data["goods_id"]
        number = request.data["number"]
        token = request.META["HTTP_AUTHORIZATION"][4:]
        print(token)
        user = jwt_decode_handler(token)
        user_id = user["user_id"]
        print("获取到的user_id: %s" % user_id)

        try:
            user = MyUser.objects.get(id=user_id)
            goods = Goods.objects.get(id=goods_id)
            Cart.objects.create(goods_id=goods,user_id=user,image_url=goods.picture,name=goods.name,
                                price=goods.price,number=number)
            return Response({"code":200,"msg":"购物车添加成功"},status=200)
        except:
            data={
                "code":500,
                "msg":"重试"
            }
            return Response(data,status=200)


# class CartInfoView(APIView):
class CartInfoView(APIView):
    def get(self, request):
        cartinfo = Cart.objects.filter(user_id_id=1)
        fields = CartSer(cartinfo, many=True)  # many 是多条数据
        data = fields.data
        res_data = {
            "code": 200,
            "data": data,
        }
        return Response(res_data, status=200)

    def put(self,request):
        # 获取vue的数据
        number = request.data["number"]
        id = request.data["id"]
        try:
            Cart.objects.filter(id=id).update(number=number)
            return Response({"code":200,"msg":"修改成功"})
        except:
            return Response({"code":500,"msg":"修改失败"})

    def delete(self,request):
        data = request.query_params #query_params 是从前端获取到的数据
        id = data["id"]
        Cart.objects.filter(id=id).delete()
        return Response({"code":200})


def get_user_id(request):
    token = request.META["HTTP_AUTHORIZATION"][4:]
    user = jwt_decode_handler(token)
    user_id = user["user_id"]
    user = MyUser.objects.get(id=user_id)
    return user


class Fenpage(APIView):
    def get(self,request):
        data = request.query_params
        page = data["page"]
        items = fenye.objects.all()   # items 是获取表里的全部信息
        pageinfo = Paginator(items,3)  # 表里的数据每三条为一页
        fenyeinfo = pageinfo.page(page)  # 获取当前页码
        fenye_list = [i for i in pageinfo.page_range]
        ser_fenye = FenSer(fenyeinfo,many=True)
        data=ser_fenye.data
        res_data = {
            "all_page":pageinfo.num_pages,
            "data":data,
            "page":fenyeinfo.number,
            "code":200,
            "msg":"ok",
            "page_list":fenye_list
        }
        return Response(status=200,data=res_data)


class Addbook(APIView):
    def post(self,request):
        name = request.data.get("name")
        read = request.data.get("read")
        commit = request.data.get("commit")
        time = request.data.get("time")
        Books.objects.create(name=name,read=read,commit=commit,time=time)
        data = {
            "code": 200,
            "msg": "添加成功"
        }
        return Response(data, status=200)


class Zhan(APIView):
    def get(self,request):
        feileiinfo = Books.objects.filter(read__gt=F("commit"))
        fields = ZhanSer(feileiinfo, many=True)  # many 是多条数据
        data = fields.data
        res={
            "code":200,
            "msg":"成功",
            "data":data
        }
        return Response(res,status=200)

    def delete(self,request):
        data = request.query_params  # query_params 是从前端获取到的数据
        id = data["id"]
        Books.objects.filter(id=id).delete()
        return Response({"code": 200})


class Addgoods(APIView):
    def post(self,request):
        data = request.data
        print("前端传过来的数据-----》",data)
        try:
            with open(data["pic"].name,"wb") as f:
                for i in data["pic"].chunks():
                    f.write(i)
            data["pic"] = data["pic"].name
            shang = ShangSer(data=data)
            shang.is_valid()
            shang.save()
            return Response(status=200,data={"code":200,"msg":"成功"})
        except:
            return Response(status=200,data={"code":500,"msg":"失败"})
